﻿using ContosoUniversity.Data;
using ContosoUniversity.Models;
using ContosoUniversity.Models.SchoolViewModels;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ContosoUniversity.Pages.Instructors
{
    public class InstructorCoursesPageModel:PageModel
    {
        public IList<AssignedCourseData> AssignedCourseDataList { get; set; }


        public void PopulateAssignedCourseData(SchoolContext _context, Instructor instructor)
        {
            var allCourses = _context.Courses;
            var instructorCourse = new HashSet<int>(instructor.CourseAssignments.Select(c=>c.CourseID));

            AssignedCourseDataList = new List<AssignedCourseData>();
            foreach (var course in allCourses)
            {
                AssignedCourseDataList.Add(new AssignedCourseData()
                {
                    CourseID=course.CourseID,
                    Title = course.Title,
                    Assigned = instructorCourse.Contains(course.CourseID)
                });
            }
        }


        public void UpdateInstructorCourses(SchoolContext _context, string[] selectedCourses, Instructor instructorToUpdate)
        {
            if (selectedCourses == null)
            {
                instructorToUpdate.CourseAssignments = new List<CourseAssignment>();
                return;
            }

            var selectedCourseHS = new HashSet<string>(selectedCourses);
            var instructorCourses = instructorToUpdate.CourseAssignments.Select(c => c.CourseID);

            foreach (var course in _context.Courses)
            {
                if (selectedCourseHS.Contains(course.CourseID.ToString()))
                {
                    if (!instructorCourses.Contains(course.CourseID))
                    {
                        instructorToUpdate.CourseAssignments.Add(new CourseAssignment()
                        {
                             CourseID=course.CourseID,
                             InstructorID = instructorToUpdate.ID
                        });
                    }
                }
                else
                {
                    if (instructorCourses.Contains(course.CourseID))
                    {
                        var courseToRemove = instructorToUpdate.CourseAssignments.SingleOrDefault(c => c.CourseID==course.CourseID);

                        _context.Remove(courseToRemove);
                    }
                }
            }
        }
    }
}
